package com.vans.practice.aqs_lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Note:
 * @Author elle
 * @Date 2020/10/5 17:28
 */
public class ConditionTest {

    final ReentrantLock lock = new ReentrantLock();
    //执行条件
    Condition notFull = lock.newCondition();
    Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[10];
    int putStr, takeStr, count;

    public void put(Object x) throws InterruptedException {
        //加锁
        lock.lock();
        System.out.println("执行put:" + putStr);
        try {
            while(count == items.length) {
                System.out.println("满了!");
                //释放锁, 加入等待队列
                notFull.await();
            }
            items[putStr] = x;
            if (++putStr == items.length) putStr = 0;
            ++count;
            //通知
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        //加锁
        lock.lock();
        System.out.println("执行take:" + takeStr);
        try {
            while(count == 0) {
                System.out.println("空了!");
                //释放锁, 加入等待队列
                notEmpty.await();
            }
            Object o = items[takeStr];
            if (++takeStr == items.length) takeStr = 0;
            --count;
            //通知
            notFull.signal();
            return o;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionTest conditionTest = new ConditionTest();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                try {
                    conditionTest.put(new Object());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(()->{
                try {
                    conditionTest.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
